﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;

namespace Universe.WCF.Behaviors.WcfStreaming
{
    public class HashReaderStream : Stream
    {
        private Stream _Parent;
        private HashAlgorithm _hashAlg;
        private int _pos = 0;

        public byte[] Hash;


        public HashReaderStream(Stream parent, HashAlgorithm hashAlg, int bufferSize)
        {
            this._Parent = new BufferedStream(parent, bufferSize);
            this._hashAlg = hashAlg;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _Parent.Dispose();

                if (_hashAlg != null)
                {
                    _hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                    Hash = _hashAlg.Hash;
                }

            }
        }

        public override void Flush()
        {
            _Parent.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int ret = _Parent.Read(buffer, offset, count);
            if (_hashAlg != null && count > 0 && ret > 0)
                _hashAlg.TransformBlock(buffer, offset, ret, buffer, offset);

            _pos += count;
            return ret;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override long Length
        {
            get { throw new NotSupportedException(); }
        }

        public override long Position
        {
            get { return _pos; }
            set { throw new NotSupportedException(); }
        }
    }
}
